<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
     <el-form-item label="学期" prop="semId">
       <el-select v-model="queryParams.semId" filterable clearable placeholder="请选择学期">
         <el-option
           v-for="item in semsterList"
           :key="item.id"
           :label="item.title"
           :value="item.id"
           size="small">
         </el-option>
       </el-select>
     </el-form-item>
    <el-form-item label="年级" prop="year">
        <el-select v-model="queryParams.year" clearable placeholder="请选择年级" >
            <el-option
            v-for="item in yearList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="专业" prop="specId">
        <el-select v-model="queryParams.specId" clearable placeholder="请选择专业" >
          <el-option
            v-for="item in specialtyList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleSubmit"
          v-hasPermi="['exam:examResult:add']"
        >提交成绩</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['exam:examResult:import']"
        >导入</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="eduTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学期" align="center" prop="semName" />
      <el-table-column label="年级" align="center" prop="year" />
      <el-table-column label="专业" align="center" prop="specName" />
      <el-table-column label="课程" align="center" prop="courseName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="教学形式" align="center" prop="mode" :formatter="modeFormat" />
      <el-table-column label="考核类型" align="center" prop="exam" :formatter="examFormat" />
      <el-table-column label="教材" align="center" prop="bookName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button v-if="scope.row.submits == 'N'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['education:eduTask:edit']"
          >录入</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-help"
            @click="handleView(scope.row)"
            v-hasPermi="['exam:examResult:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleStudent(scope.row)"
            v-hasPermi="['exam:examResult:export']"
          >名单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教学任务对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="880px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="学期" prop="semId">
            <el-select v-model="form.semId" filterable disabled clearable placeholder="请选择学期">
              <el-option
                v-for="item in semsterList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
                size="small">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程" prop="courseId">
           <el-select v-model="form.courseId" placeholder="请输入课程" clearable filterable disabled>
             <el-option
               v-for="dict in courseList"
               :key="dict.id"
               :label="dict.title"
               :value="dict.id"
             />
           </el-select>
          </el-form-item>
          <el-table v-loading="loading" :data="studentList" v-if="form.exam == '1'">
            <el-table-column label="学号" align="center" prop="code" />
            <el-table-column label="姓名" align="center" prop="name" />
            <el-table-column label="平时成绩" prop="result1">
              <template slot-scope="scope">
                <el-input-number size="mini" :disabled="view" :min="0" :max="100" :precision="1" v-model="studentList[scope.$index]['result1']" :step="1" @change="saveResult(scope.row)" placeholder="请输入分数" />
              </template>
            </el-table-column>
            <el-table-column label="期中成绩" prop="result2">
              <template slot-scope="scope">
                <el-input-number size="mini" :disabled="view" :min="0" :max="100" :precision="1" v-model="studentList[scope.$index]['result2']" :step="1" @change="saveResult(scope.row)" placeholder="请输入分数" />
              </template>
            </el-table-column>
            <el-table-column label="期末成绩" prop="result3">
              <template slot-scope="scope">
                <el-input-number size="mini" :disabled="view" :min="0" :max="100" :precision="1" v-model="studentList[scope.$index]['result3']" :step="1" @change="saveResult(scope.row)" placeholder="请输入分数" />
              </template>
            </el-table-column>
            <el-table-column label="实操/实验" prop="result4">
              <template slot-scope="scope">
                <el-input-number size="mini" :disabled="view" :min="0" :max="100" :precision="1" v-model="studentList[scope.$index]['result4']" :step="1" @change="saveResult(scope.row)" placeholder="请输入分数" />
              </template>
            </el-table-column>
          </el-table>

          <el-table v-loading="loading" :data="studentList" v-if="form.exam == '2'">
            <el-table-column label="学号" align="center" prop="code" />
            <el-table-column label="姓名" align="center" prop="name" />
            <el-table-column label="成绩级别" prop="level">
              <template slot-scope="scope">
                <el-select size="mini" :disabled="view" v-model="studentList[scope.$index]['level']" @change="saveResult(scope.row)" clearable>
                  <el-option
                    v-for="dict in levelOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的实习任务数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEduTask, myEduTask, getEduTask, submitTaskResult, exportEduTask } from "@/api/education/eduTask";
import { exportExamStudent, saveExamStudent, listExamStudent } from "@/api/exam/examResult";
import { getToken } from "@/utils/auth";
import { selectSpecialty} from "@/api/base/specialty";
import { selectSemster} from "@/api/base/semster";
import { selectClazz } from "@/api/base/clazz";
import { selectCourse} from "@/api/base/course";

export default {
  name: "EduTask",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学期数据
      semsterList: [],
      //起始年
      yearList:[],
      // 专业表格数据
      specialtyList: [],
      // 课程数据
      courseList: [],
      // 班级数据
      classList: [],
      // 教学任务表格数据
      eduTaskList: [],
      //学生列表
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 教学形式字典
      modeOptions: [],
      // 考核类型字典
      examOptions: [],
      // 成绩级别字典
      levelOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        semId: null,
        specId: null,
        courseId: null,
        mode: null,
        classId: null,
        teacherId: null,
        exam: null,
        result: null,
        bookId: null,
        roomId: null,
        score: null,
        periods: null,
        startWeek: null,
        endWeek: null,
        addTime: null,
        addUser: null,
        updateUser: null,
        status: 'Y'
      },
      resultSet:'',
      // 表单参数
      form: {},
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/exam/examResult/importData"
      },
      // 表单校验
      rules: {
        year: [
          { required: true, message: "年级不能为空", trigger: "blur" }
        ],
        semId: [
          { required: true, message: "学期不能为空", trigger: "blur" }
        ],
        specId: [
          { required: true, message: "专业不能为空", trigger: "blur" }
        ],
        courseId: [
          { required: true, message: "课程不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "教师不能为空", trigger: "blur" }
        ],
        bookId: [
          { required: true, message: "教材不能为空", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "教室不能为空", trigger: "blur" }
        ],
        periods: [
          { required: true, message: "学时不能为空", trigger: "blur" }
        ],
        startWeek: [
          { required: true, message: "开始周不能为空", trigger: "blur" }
        ],
        endWeek: [
          { required: true, message: "结束周不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("result_level").then(response => {
      this.levelOptions = response.data;
    });
    this.getDicts("education_mode").then(response => {
      this.modeOptions = response.data;
    });
    this.getDicts("exam_type").then(response => {
      this.examOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.statusOptions = response.data;
    });
    this.getConfigKey("sys.time.start").then(response => {
      var st = parseInt(response.msg);
      var dt = new Date();
      while(st<=dt.getFullYear()+1){
        this.yearList.push({value: st,label: st});
        st ++;
      }
    });
    this.getConfigKey("edu.result.set").then(response => {
      this.resultSet = response.msg;
    });
    selectSpecialty({'status':1}).then(response => {
      this.specialtyList = response.rows;
    });
    selectSemster({'status':1}).then(response => {
      this.semsterList = response.rows;
    });
    selectCourse().then(response => {
        this.courseList = response.rows;
        this.total = response.total;
      });
    selectClazz().then(response => {
        this.classList = response.rows;
        this.total = response.total;
      });
  },
  methods: {
    /** 查询教学任务列表 */
    getList() {
      this.loading = true;
      myEduTask(this.queryParams).then(response => {
        this.eduTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 教学形式字典翻译
    modeFormat(row, column) {
      return this.selectDictLabel(this.modeOptions, row.mode);
    },
    // 考核类型字典翻译
    examFormat(row, column) {
      return this.selectDictLabel(this.examOptions, row.exam);
    },
    // 确认状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        semId: null,
        specId: null,
        courseId: null,
        mode: null,
        classId: null,
        teacherId: null,
        exam: "1",
        result: this.resultSet.replace(/\s/g,"\r\n"),
        bookId: null,
        roomId: null,
        score: null,
        periods: null,
        startWeek: null,
        endWeek: null,
        addTime: null,
        addUser: null,
        updateTime: null,
        updateUser: null,
        status: "N"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 录入按钮操作 */
    handleUpdate(row) {
      this.reset();
      getEduTask(row.id).then(response => {
        this.form = response.data;
        listExamStudent(row.id).then(response => {
          this.studentList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        this.open = true;
        this.view = false;
        this.title = "在线录入成绩";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      getEduTask(row.id).then(response => {
        this.form = response.data;
        listExamStudent(row.id).then(response => {
          this.studentList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        this.open = true;
        this.view = true;
        this.title = "查看成绩";
      });
    },
    /** 提交按钮 */
    handleSubmit(row) {
      const ids = row.id || this.ids;
      this.$confirm('提交成将无法录入和修改成绩，您是否确认要将选中的教学任务设置为成绩已提交状态?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return submitTaskResult(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        });
    },

    /** 保存成绩 */
    saveResult(row) {
      var data = row;
      for(var i=0;i<this.studentList.length;i++){
        if(row.studentId == this.studentList[i]['studentId']){
          data = this.studentList[i];
        }
      }
      saveExamStudent(data).then(response => {
        this.msgSuccess("保存成功");
      });
    },
    /** 导出按钮操作 */
    handleStudent(row) {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有该教学任务下的学生名单吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportExamStudent(row.id);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "成绩导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
